package net.hzlj.platform.enterprise.utils.recorder;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;

/**
 * @ClassName: MediaManager
 * @Description: 音频播放
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2016-1-12 09:02:23
 */
public class MediaManager {

    private static MediaPlayer mMediaPlayer;
    private static boolean isPause;// 是否暂停

    public static boolean isRunning = false;
    public static String recordingPath = "";

    /**
     * 播放音频
     *
     * @param filePath
     * @param onCompletionListener
     */
    public static void playSound(String filePath,
                                 OnCompletionListener onCompletionListener) {
        if (null == mMediaPlayer) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnErrorListener(new OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mMediaPlayer.reset();
                    return false;
                }
            });
        } else {
            mMediaPlayer.reset();
        }

        try {
            recordingPath = filePath;
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnCompletionListener(onCompletionListener);
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            isRunning = true;
        } catch (Exception e) {
            e.printStackTrace();
            recordingPath = filePath;
        }
    }

    /**
     * 暂停播放
     */
    public static void pause() {
        if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            isPause = true;
            isRunning = false;
        }
    }

    /**
     * 继续播放
     */
    public static void resume() {
        if (null != mMediaPlayer && isPause) {
            mMediaPlayer.start();
            isRunning = true;
            isPause = false;
        }
    }

    /**
     * 停止并释放资源
     */
    public static void release() {
        if (null != mMediaPlayer) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            isRunning = false;
            mMediaPlayer.release();
            mMediaPlayer = null;
            recordingPath = null;
        }
    }
}
